<template>
  <div class="video-page">
    <!-- 筛选区域 -->
    <div class="filter-container">

      <div class="search-upload">
        <div class="search-container">
          <input 
            v-model="searchQuery" 
            placeholder="搜索视频名称" 
            class="search-input" 
          />
          <img 
            src="@/assets/picture/find.png" 
            @click="searchVideos" 
            alt="搜索" 
            class="search-icon"
          />
        </div>
      </div>
    </div>

    <!-- 视频列表 -->
    <div class="video-list">
      <div
        class="video-card"
        v-for="video in paginatedVideos"
        :key="video.resource_id"
        :data-id="video.resource_id"
        @click="handleSelect(video)"
      >
        <div class="video-cover-container" @click="openVideo(video.resource_url)">
          <img 
            :src="video.video_cover || defaultCover" 
            alt="视频封面" 
            class="video-cover" 
          />
          <img 
            src="@/assets/picture/play.png" 
            alt="播放" 
            class="play-icon" 
          />
        </div>
        <div class="video-info">
          <span>{{ video.resource_name }}</span>
          <p>{{ formatDate(video.create_time) }}</p>
        </div>
        <div class="favorite-icon" @click.stop="toggleFavorite(video)">
          <img 
            :src="video.isFavorite ? require('@/assets/picture/star-solid.png') : require('@/assets/picture/star.png')" 
            :alt="video.isFavorite ? '已收藏' : '未收藏'" 
          />
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button class="btn" @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>当前页: {{ currentPage }} / {{ totalPages }}</span>
      <button class="btn" @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
    
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { fetchStudentResources} from "@/services/api";
import { addStudentFavorite, removeStudentFavorites } from '@/services/api';

export default {
  name: "VideosPage",
  setup(props, context) {
    const userId = ref(localStorage.getItem('id')); 
    const router = useRouter();
    const videos = ref([]);
    const currentFilter = ref("all");
    const searchQuery = ref("");
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const fileInput = ref(null);
    const defaultCover = "https://via.placeholder.com/300x150?text=No+Cover";

    // 获取技术ID和令牌
    const getTechIdAndToken = () => {
      const techId = localStorage.getItem("id");
      const token = localStorage.getItem("token");
      return { techId, token };
    };
     const handleSelect = (video) => {
      const selectedVideo = {
        id: video.resource_id,
        name: video.resource_name,
        type: 'video',
        uploadTime: video.create_time,
        url: video.resource_url
      };
      context.emit('video-selected', selectedVideo);  // 使用 context.emit
    };

    // Fetch videos based on filter and search query
    const fetchVideos = () => {
  const { techId } = getTechIdAndToken();

  fetchStudentResources(techId, 'video')
    .then((response) => {
      if (response.data.status === 1) {
        videos.value = response.data.data.map(video => ({
          ...video,
           isFavorite: true ,
            re_star_id: video.re_star_id
        }));
      }
    })
    .catch(error => {
      console.error('请求错误:', error);
    });
};
const filteredVideos = computed(() => {
  return videos.value.filter(video => 
    video.resource_name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

    const searchVideos = () => {
      currentPage.value = 1;
      fetchVideos();
    };
    const paginatedVideos = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredVideos.value.slice(start, end);
    });

    const totalPages = computed(() => Math.ceil(filteredVideos.value.length / itemsPerPage));

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };



    const openVideo = (videoUrl) => {
      window.open(videoUrl, "_blank");
    };

    const formatDate = (dateString) => {
      const date = new Date(dateString);
      return date.toLocaleString();
    };

    onMounted(() => {
      const { techId, token } = getTechIdAndToken();
      if (techId && token) {
        fetchVideos();
      } else {
        console.error('用户未登录。重定向到登录页面。');
        router.push('/login');
      }
    });

const toggleFavorite = async (video) => {
  if (video.isFavorite) {
    // 取消收藏
    try {
      const res = await removeStudentFavorites(video.re_star_id);
      if (res.data.status === 1) {
        video.isFavorite = false;
        video.re_star_id = null;
        ElMessage.success("取消收藏成功");
      } else {
        ElMessage.error("取消收藏失败");
      }
    } catch (err) {
      console.error("取消收藏失败：", err);
      ElMessage.error("网络错误，取消收藏失败");
    }
  } else {
    // 添加收藏
    try {
      const res = await addStudentFavorite({
        user_id: userId.value,
        resource_id: video.resource_id
      });
      if (res.data.status === 1) {
        video.isFavorite = true;
        // TODO：若后端返回 re_star_id 可这样更新
        // video.re_star_id = res.data.data.re_star_id;
        ElMessage.success("收藏成功");
      } else {
        ElMessage.error("收藏失败");
      }
    } catch (err) {
      console.error("收藏失败：", err);
      ElMessage.error("网络错误，收藏失败");
    }
  }
};
    return {

      toggleFavorite,
      videos,
      currentFilter,
      searchQuery,
      currentPage,
      paginatedVideos,
      totalPages,
      defaultCover,
      fetchVideos,
      searchVideos,
      openVideo,
      formatDate,
      prevPage,
      nextPage,
      fileInput,
      handleSelect
    };
  },
};
</script>

<style scoped>
.favorite-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: white;
  border-radius: 50%;
  padding: 6px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
  z-index: 10;
}

.favorite-icon img {
  width: 16px;
  height: 16px;
}

.video-card:hover .favorite-icon {
  opacity: 1;
}
.video-page {
  padding: 20px;
  min-height: 70vh;
  display: flex;          /* 新增 */
  flex-direction: column; /* 新增 */
}
.search-container {
  position: relative;
  display: flex;
  align-items: center;
}
h1 {
  text-align: center;
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}


.search-upload {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px; /* 为搜索图标留出空间 */
  border-radius: 20px;
}

.search-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  width: 20px;
  height: 20px;
}

.btn {
  padding: 8px 12px;
  cursor: pointer;
  border: none;
  border-radius: 4px;
  background-color: #e0e0e0;
  transition: background-color 0.3s;
}

.upload-btn {
  background-color: #125AA2;
  color: #fff;
}

.upload-btn:hover {
  background-color: #3987d4;
}

.btn-rename {
  background-color: #125AA2;
  font-size: 13px;
  color: #fff;
  padding: 6px 12px;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-right: 5px; /* 确保按钮之间有间隔 */
}

.btn-rename:hover {
  background-color: #3987d4;
}

.btn-delete {
  background-color: #E85C5C;
  color: #fff;
  font-size: 13px;
  padding: 6px 12px;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-delete:hover {
  background-color: #d32f2f;
}

.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
}

.video-card {
  border: 1px solid #dddddd85; /* 修正边框语法 */
  border-radius: 5px;
  background-color: #fff;
  text-align: center;
  position: relative;
  transition: transform 0.2s;
}

.video-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.video-cover-container {
  position: relative;
  cursor: pointer; /* 更改鼠标为手型 */
}

.video-cover {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0; /* 默认隐藏 */
  transition: opacity 0.3s ease; /* 平滑过渡 */
  width: 60px; /* 根据需要调整大小 */
  height: 60px;
  pointer-events: none; /* 允许点击事件传递到下方元素 */
}

.video-card:hover .play-icon {
  opacity: 0.9; /* 悬停时显示 */
}
.video-card:hover img {
  opacity: 0.9; 
}


.video-info {
  margin-top: 10px;
  /* cursor: pointer; */ /* 移除 cursor 以避免误导用户点击事件 */
}

.video-info span {
  display: block;
  font-size: 13px;
  font-weight: bold;
  margin: 0px 10px;
  color: #333333c9;
  white-space: nowrap;
  overflow: hidden;
}

.video-info p {
  margin-top: 5px;
  font-size: 10px;
  color: rgba(119, 119, 119, 0.863);
}

.rename-input {
  padding: 5px 8px;
  margin-top: 5px;
  border: 1px solid #2196f3;
  border-radius: 4px;
}

.button-group {
  display: flex;
  justify-content: center;
  margin: 10px 0px 15px 0px;
}

.pagination {
    gap: 10px;
    flex-wrap: wrap;
    position: absolute;
    bottom: 20px;
    left: 50%;
}

.pagination .btn {
  padding: 8px 12px;
  cursor: pointer;
  border: none;
  background-color: #2196f3;
  color: #fff;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.pagination .btn:disabled {
  background-color: #b0bec5;
  cursor: not-allowed;
}

.pagination .btn:not(:disabled):hover {
  background-color: #1976d2;
}

.pagination span {
  font-size: 16px;
  color: #333;
}
</style>

